/**
 * All rights Reserved, Designed By 溪云阁
 * Copyright:    Copyright(C) 2016-2020
 */

package com.module.boots.oss;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import lombok.extern.slf4j.Slf4j;

/**
 * OSS文件上传工具
 * @author：溪云阁
 * @date：2020年5月16日
 */
@Component
@Slf4j
public class AliyunOssUtils {

    @Autowired
    private AliyunOSSProperties properties;

    /**
     * 上传文件到阿里云 OSS 服务器
     * @author 溪云阁
     * @param files 文件
     * @param fileTypeEnum 文件类型
     * @return List<String>
     */
    public List<String> uploadFile(MultipartFile[] files, String storagePath, FileTypeEnum fileTypeEnum) {

        // 创建OSSClient实例
        final OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        final List<String> fileIds = new ArrayList<>();
        try {
            for (final MultipartFile file : files) {
                // 创建一个唯一的文件名，类似于id，就是保存在OSS服务器上文件的文件名(自定义文件名)
                String fileName = UUID.randomUUID().toString();
                final InputStream inputStream = file.getInputStream();
                // 设置对象
                final ObjectMetadata objectMetadata = new ObjectMetadata();
                // 设置数据流里有多少个字节可以读取
                objectMetadata.setContentLength(inputStream.available());
                objectMetadata.setCacheControl("no-cache");
                objectMetadata.setHeader("Pragma", "no-cache");
                objectMetadata.setContentType(file.getContentType());
                objectMetadata.setContentDisposition("inline;filename=" + fileName);
                fileName = storagePath + "/" + fileName;
                // 上传文件
                final PutObjectResult result = ossClient.putObject(properties.getBucketName(), fileName, inputStream, objectMetadata);
                log.info("Aliyun OSS AliyunOSSUtil.uploadFileToAliyunOSS,result:{}", result);
            }
        }
        catch (final IOException e) {
            log.error("Aliyun OSS AliyunOSSUtil.uploadFileToAliyunOSS fail,reason:{}", e);
        }
        finally {
            ossClient.shutdown();
        }
        return fileIds;
    }

    /**
     * 删除文件
     * @author 溪云阁
     * @param fileName void
     */
    public void deleteFile(String fileName) {
        final OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        try {
            ossClient.deleteObject(properties.getBucketName(), fileName);
        }
        catch (final Exception e) {
            log.error("{}", e.fillInStackTrace());
        }
        finally {
            ossClient.shutdown();
        }
    }

    /**
     * 判断文件是否存在
     * @author 溪云阁
     * @param fileName 文件名称
     * @return boolean
     */
    public boolean doesObjectExist(String fileName) {
        final OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        try {
            if (Strings.isEmpty(fileName)) {
                log.error("文件名不能为空");
                return false;
            } else {
                final boolean found = ossClient.doesObjectExist(properties.getBucketName(), fileName);
                return found;
            }
        }
        finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
